package top.honlnk.common.network;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import top.honlnk.common.constant.UserConstant;
import top.honlnk.common.exception.CustomException;
import top.honlnk.pojo.entity.OcrAdminInfo;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class GetImageOCRDataNetwork {

    public JSONObject getImageOCRData(String base64EncodedFile, OcrAdminInfo ocrAdminInfo){
        // 目标URL
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/table" + "?access_token=" + ocrAdminInfo.getAccessToken();

        JSONObject responseObject = null;

        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(url);

            // 设置Header
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 设置Body参数，这里直接构造请求体字符串，实际应用中可能需要根据API要求调整
            base64EncodedFile = URLEncoder.encode(base64EncodedFile, StandardCharsets.UTF_8);
//            log.info("image：{}", base64EncodedFile);
            String requestBody = "image=" + base64EncodedFile;
            StringEntity entity = new StringEntity(requestBody, "UTF-8");
            httpPost.setEntity(entity);

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 检查响应状态码
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 读取并处理响应内容
                    HttpEntity responseEntity = response.getEntity();
                    if (responseEntity != null) {
                        String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                        // 将 responseString 解析为一个 JSONObject 对象并赋值给 responseObject，便于后续处理 JSON 数据。
                        responseObject = new JSONObject(responseString);
                        if (responseObject.has("error_code")) {

                            // 如果error_code等于 "111" 且 error_msg 等于 "Access token expired" 的话 或error_code等于 "110" error_msg 等于 "Access token invalid or no longer valid" 的话
                            if (responseObject.getInt("error_code") == 111 && responseObject.getString("error_msg").equals("Access token expired") ||
                            responseObject.getInt("error_code") == 110 && responseObject.getString("error_msg").equals("Access token invalid or no longer valid")) {
                                responseObject.put("custom_error", UserConstant.ACCESS_TOKEN_EXPIRED);
                                log.error(UserConstant.OCR_TOKEN_EXPIRED, responseObject);
                            }
                        }
                    }
                } else {
                    log.error(UserConstant.REQUEST_FAIL_LOG, response.getStatusLine().getStatusCode());
                    log.error(UserConstant.RESPONSE_BODY, response);
                    throw new CustomException(UserConstant.REQUEST_FAIL + response.getStatusLine().getStatusCode());
                }
            } catch (JSONException e) {
                log.error(UserConstant.JSON_PARSE_ERROR, e);
                throw new CustomException(e.getMessage());
            }
        } catch (IOException e) {
            log.error(UserConstant.SEND_REQUEST_FAIL, e);
            throw new CustomException(e.getMessage());
        }
        return responseObject;
    }
}
